//
//  EventsViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/1/28.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
import ThPullRefresh

class EventsViewController: UITableViewController {
    var projectType: Int!
    var events: [GTEvent] = []
    var eventCell : EventCell!
    var page: NSInteger = 1
    var userID: NSInteger = 0
    var private_token: String!
    var isHeadRefresh: Bool
    
    init(userID: NSInteger) {
        self.isHeadRefresh = true
        self.userID = userID
        
        super.init(nibName: nil, bundle: nil)
    }
    
    init(privateToken: String) {
        self.isHeadRefresh = true
        self.private_token = privateToken
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "EventCell", bundle: nil), forCellReuseIdentifier: "eventCell")
        eventCell = self.tableView.dequeueReusableCellWithIdentifier("eventCell") as! EventCell
        
        self.fetchForEvents()

        self.tableView.tableFooterView = UIView()
        self.tableView.addHeadRefresh(self) { () -> () in
            
            self.isHeadRefresh = true
            self.page = 1
            self.fetchForEvents()
        }
        self.tableView.addFootRefresh(self) { () -> () in
            
            self.isHeadRefresh = false
            ++self.page
            self.fetchForEvents()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if events.count > 0 {
            return events.count
        }
        return 0
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let eventCell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventCell
        if events.count > 0 {
            let event = events[indexPath.row] as GTEvent
            let action = Util()
            
            let url:NSURL = NSURL(string: "https://git.oschina.net/"+(event.author?.portrait)!)!
            eventCell.portrait.kf_setImageWithURL(url, placeholderImage:UIImage.init(named: "portrait_loading"))
            eventCell.TitleLabel.text = action.getEventDescription(event)
            action.getEventContentView(eventCell.contentLabel, event: event)
            eventCell.timeLable.text = event.createdAt?.componentsSeparatedByString("T")[0]
        }
        
        return eventCell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row < events.count {
            let event = events[indexPath.row] as GTEvent
            let action = Util()
            
            eventCell.TitleLabel.text = action.getEventDescription(event)
            var height = eventCell.TitleLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
            eventCell.contentLabel.text = action.getEventContentView(eventCell.contentLabel, event: event)
            height = eventCell.contentLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + height
            
            return height + 57
        }
        return 110
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
        
        let projectDetailVC = ProjectDetailViewController(projectID: events[indexPath.row].projectId!, namespace: (events[indexPath.row].project?.nameSpace)!)
        projectDetailVC.title = events[indexPath.row].project?.name
        projectDetailVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(projectDetailVC, animated: true)
    }

    //获取数据
    func fetchForEvents() -> Void {
        var eventUrl: String!
        
        if userID > 0 {
            eventUrl = "https://git.oschina.net/api/v3/events/user/"+"\(userID)"+"?page="+"\(page)"
        } else {
            eventUrl = "https://git.oschina.net/api/v3/events?private_token=\(private_token)"+"&page="+"\(page)"
        }
        
        if self.isHeadRefresh {
            self.events.removeAll(keepCapacity: Bool())
        }
        
        Alamofire.Manager.sharedInstance.request(Method.GET, eventUrl).responseJSON { response in
            if let results = response.result.value {
                let jsonArray = JSON(results).array!

                for i in 0 ..< jsonArray.count {
                    let event = GTEvent(json: jsonArray[i])
                    self.events.append(event)
                }
                
                self.tableView.reloadData()
                self.tableView.tableHeadStopRefreshing()
                self.tableView.tableFootStopRefreshing()
            }
        }
    }
}
